/*
 * Lenovo Group
 * Copyright (c) 2015-2016 All Rights Reserved.
 * Project Name: lmrp-android app
 * Create Time: 16-2-19 下午3:15
 */

package com.lenovo.mso2o.ui;

import android.app.Activity;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.reflect.TypeToken;
import com.lenovo.framework.base.BaseDialogFragment;
import com.lenovo.framework.base.BaseSecondaryActivity;
import com.lenovo.framework.biz.ContextManager;
import com.lenovo.framework.conf.FConstants;
import com.lenovo.framework.entity.FGson;
import com.lenovo.framework.entity.Res;
import com.lenovo.framework.service.LocationService;
import com.lenovo.framework.ui.BridgedX5WebViewFragment;
import com.lenovo.framework.ui.UIWeakRefHandler;
import com.lenovo.framework.util.DLog;
import com.lenovo.framework.util.FileHelper;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;
import com.lenovo.mso2o.conf.JSAction;
import com.lenovo.mso2o.conf.MSConstants;
import com.lenovo.mso2o.entity.Order;
import com.lenovo.mso2o.entity.OrderMenu;
import com.lenovo.mso2o.entity.g.Site;
import com.lenovo.mso2o.entity.g.SiteDao;
import com.lenovo.mso2o.ui.fragment.ChoiceConditionDialogFragment;
import com.lenovo.mso2o.ui.fragment.ConfirmDialogFragment;
import com.lenovo.mso2o.ui.fragment.DecoderFragment;
import com.lenovo.mso2o.ui.fragment.ImageFragment;
import com.lenovo.mso2o.ui.fragment.LocationChoiceConditionDialogFragment;
import com.lenovo.mso2o.ui.fragment.OrderContentMoreDialogFragment;
import com.lenovo.mso2o.ui.fragment.POISearchDialogFragment;
import com.lenovo.mso2o.ui.fragment.TalkbackDialogFragment;
import com.lenovo.mso2o.ui.fragment.TimepickerDialogFragment;
import com.lenovo.mso2o.ui.fragment.WritePadDialogFragment;
import com.lenovo.mso2o.util.ActionCallbacks;
import com.lenovo.mso2o.util.CommonUtil;
import com.lenovo.mso2o.util.FileCacheUtil;
import com.lenovo.framework.util.FileSizeHelper;
import com.lenovo.mso2o.util.MediaPathUtils;
import com.lenovo.mso2o.util.Utils;
import com.trello.rxlifecycle.components.support.RxFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class WebActivity extends BaseSecondaryActivity implements BridgeHandler, BaseDialogFragment.DialogFragmentDismissListener, BridgedX5WebViewFragment.TitleUpdater, LocationService.LocationSuccessListener, ConfirmDialogFragment.DialogClickListener {

    public static final int REQUEST_LOCATION = 0x31;
    public static final String EXTRA_PATH = "extra_path";
    private static final String CONFIRM = "dialog_confirm";
    public static final String PARENT_FUNCTION_NAME = "parent_function_name";
    public static final String PARENT_FUNCTION_DATA = "parent_function_data";
    public static final int REQUEST_SUBPAGE_DATA = 0x35;
    public static final String ORDER = "order_item";
    private String title;
    public static final int FILECHOOSER_RESULTCODE = 0x01;
    public static final int TAKEPICTURE_REQUESTCODE = 0x02;
    public static final int GET_PICTURE_FROMTHUMB_REQUESTCODE = 0x03;
    public static final int CHOOSE_DATE = 0x04;//选择时间标志位
    public static final int RECORD_VOICE = 0x05;//录音标志位
    public static final int CHOOSE_LIST = 0x06;//打开文件浏览器标志位
    public static final int REQUEST_STEP = 0x32;
    public static final int REQUEST_OPENFILE = 0x34;//打开图片Action的key
    public static final String ORDER_ID = "order_id";
    public boolean sign = false;
    //private UrlSaverDao saverDao;

    public static Res res = new Res();
    public CallBackFunction delayCallback;
    private FragmentManager manager;
    BridgedX5WebViewFragment webFragment;
    private JSONObject object;
    private String url;
    private static final int OVER = 1;

    String choiceTag = "choice";
    String locationChoiceTag = "choice";
    String talkTag = "talk";
    String moreTag = "more";
    String timeTag = "time";
    private ServiceConnection conn;
    Intent intent;
    private String ticketid;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //saverDao = MSApplication.getDaoSession().getUrlSaverDao();
        manager = getSupportFragmentManager();

        intent = new Intent(this, LocationService.class);
        conn = LocationService.connection(this, intent);
        url = getIntent().getStringExtra(FConstants.X5WEBVIEW_INITIAL_URL);
        if (getIntent().getSerializableExtra(ORDER) == null) {
            Order order = new Order();
            order.setTicketid("" + Long.MAX_VALUE);
            getIntent().putExtra(ORDER, order);
        }
        ticketid = ((Order) getIntent().getSerializableExtra(ORDER)).getTicketid();
        /*
        String ticketid = ((Order) getIntent().getSerializableExtra(ORDER)).getTicketid();
        DLog.w("url", url + " id:" + ticketid);
        int idx = url.indexOf("#");
        if (idx < 0) {
            idx = url.length();
        }
        DLog.i("likes", url.substring(0, idx));
        List<UrlSaver> savers = saverDao.queryBuilder().where(UrlSaverDao.Properties.Ticketid.eq(ticketid)).where(UrlSaverDao.Properties.Url.like("%" + url.substring(0, idx) + "%")).list();
        if (savers != null && savers.size() == 1) {
            url = savers.get(0).getUrl();
            DLog.w("url redirect", url + " ticketid:" + ticketid);
        }
        */
        pushWebFragment(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //if (!sign && url.contains(MSConstants.)) {
        //   webFragment.send("resume", this);
        // }
    }


    private void pushWebFragment(String url) {
        webFragment = BridgedX5WebViewFragment.newInstance(url);
        webFragment.setDefaultBridgeHandler(this);
        webFragment.setOnTitleReceiveHandler(this);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in the fragment_container view with this webFragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fragment_container, webFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    public void locateForSign(WebActivity webActivity) {
        //重新开始定位，如果超过3秒，还没有拿到位置，调actionCallbacks, 提示传入照片, 如果已经关闭提示框
        //再次bind
        bindService(intent, conn, BIND_AUTO_CREATE);
        //显示ProgressDialog
        processPreview(getString(R.string.get_Location), null, false);
        new UIWeakRefHandler<WebActivity>(this).postDelayed(new Runnable() {
            @Override
            public void run() {
                processDismiss();
                ActionCallbacks.autoSign(object, WebActivity.this, delayCallback, true);
            }
        }, 5000);
    }

    protected String getActionBarTitleString() {
        return title;
    }

    public void updateTitle(String title) {
        this.title = title;
        super.updateTitle();
    }

    public void refresh() {
        if (CommonUtil.isNetworkAvailable(this)) {
            if (webFragment != null)
                webFragment.clearCacheAndRefresh();
        } else {
            showShortToast(R.string.network_isnot_available);
        }
    }

    public String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_web;
    }

    @Override
    public void onDetachedFromWindow(){
        super.onDetachedFromWindow();
        if(webFragment != null) {
            webFragment = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //delayCallback = null;
        if (conn != null) {
            try {
                unbindService(conn);
            }catch (Exception e){}
        }
    }


    @Override
    public void handler(String data, CallBackFunction function) {
        res.setResult(new Object());
        try {
            object = new JSONObject(data);
            final int code = object.getInt("actionCode");
            if (code == JSAction.GET_PICTURE.getValue()) {
                JSONObject datas = object.getJSONObject("data");
                boolean isDir = datas.getBoolean("isDir");
                boolean isSignature = datas.getBoolean("isSignature");
                if (!isSignature) {
                    res = ActionCallbacks.takePhoto(this, function, isDir);
                } else {
                    WritePadDialogFragment writePadDialogFragment = new WritePadDialogFragment();
                    writePadDialogFragment.show(getSupportFragmentManager(), "writepad");
                    res = null;
                }
            } else if (code == JSAction.OPEN_FILE.getValue()) {
                res = ActionCallbacks.openFile(this, object);
            } else if (code == JSAction.CHOOSE_FILE.getValue()) {
                res = ActionCallbacks.chooseFile(this);
            } else if (code == JSAction.RETRIEVE_H5DATA_TO_PARENT.getValue()) {
                res = ActionCallbacks.retrieveData(object, this);
            } else if (code == JSAction.CHOOSE_LIST.getValue()) {
                ChoiceConditionDialogFragment dialogFragment = new ChoiceConditionDialogFragment();
                Bundle bundle = new Bundle();
                JSONObject datas = object.getJSONObject("data");
                bundle.putInt(ChoiceConditionDialogFragment.POSITION, datas.getInt("selected"));
                bundle.putBoolean(ChoiceConditionDialogFragment.IS_MENU_OR_NOT, "menu".equals(datas.getString("type")));
                bundle.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                JSONArray array = datas.getJSONArray("items");
                ArrayList<String> list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    list.add(array.getString(i));
                }
                bundle.putStringArrayList(ChoiceConditionDialogFragment.STRING_LIST, list);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(manager, choiceTag);
                res = null;
            } else if (code == JSAction.CHOOSE_TIME.getValue()) {
                TimepickerDialogFragment timeFragment = new TimepickerDialogFragment();
                timeFragment.show(manager, timeTag);
                res = null;
            } else if (code == JSAction.RECORD_VOICE.getValue()) {
                TalkbackDialogFragment talkFragment = new TalkbackDialogFragment();
                talkFragment.show(manager, talkTag);
                res = null;
            } else if (code == JSAction.OPEN_VOICE.getValue()) {
                res = ActionCallbacks.openVoice(object, function, this);
            } else if (code == JSAction.SCAN_QRCODE.getValue()) {
                res = ActionCallbacks.scanQrCode(this);
            } else if (code == JSAction.POST_DATA.getValue()) {
                res = ActionCallbacks.postData(object, this, function);
            } else if (code == JSAction.CALL.getValue()) {
                res = ActionCallbacks.callPhone(object, this);
            } else if (code == JSAction.MORE_MENU.getValue()) {
                OrderContentMoreDialogFragment orderMoreFragment = new OrderContentMoreDialogFragment();
                Bundle b = new Bundle();
                JSONArray array = new JSONObject(data).getJSONArray("data");
                ArrayList<OrderMenu> list = FGson.gson().fromJson(array.toString(), new TypeToken<ArrayList<OrderMenu>>() {
                }.getType());
                b.putParcelableArrayList(OrderContentMoreDialogFragment.MENU, list);
                orderMoreFragment.setArguments(b);
                orderMoreFragment.show(manager, moreTag);
                res = null;
            } else if (code == JSAction.GOTO.getValue()) {
                res = ActionCallbacks.gotoPage(object, this);
            } else if (code == JSAction.AUTO_SIGN.getValue()) {
                res = ActionCallbacks.autoSign(object, this, function, false);
            } else if (code == JSAction.TOAST.getValue()) {
                if(!TextUtils.isEmpty(object.getJSONObject("data").getString("tip")))
                    if (!this.getString(R.string.sign_faraway).equals(object.getJSONObject("data").getString("tip"))) {
                        showShortToast(object.getJSONObject("data").getString("tip"));
                    }
                res.setStatus(1);
            } else if (code == JSAction.NAVIGATION.getValue()) {
                res = ActionCallbacks.navigation(LocationService.getRealTimeLatLngTimeless(), object, this);
            } else if (code == JSAction.SEARCH.getValue()) {
                res = ActionCallbacks.search(object, this);
            } else if (code == JSAction.CONFIRM.getValue()) {
                JSONObject datas = object.getJSONObject("data");
                String title = datas.getString("title");
                String message = datas.getString("message");
                ConfirmDialogFragment fragment = ConfirmDialogFragment.newInstance(title, message);
                fragment.setListener(this);
                fragment.show(getSupportFragmentManager(), CONFIRM);
                res = null;
            } else if (code == JSAction.SELECT_LOCATION.getValue()) {
                LocationChoiceConditionDialogFragment locationdialogFragment = new LocationChoiceConditionDialogFragment();
                locationdialogFragment.show(manager, locationChoiceTag);
                Bundle bundle = new Bundle();
                bundle.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                locationdialogFragment.setArguments(bundle);
                res = null;
            } else if (code == JSAction.SEARCH_LOCATION.getValue()) {
                DialogFragment search = new POISearchDialogFragment();
                Bundle b = new Bundle();
                b.putString(POISearchDialogFragment.TYPE_KEY, "site");
                b.putBoolean(BaseDialogFragment.DISMISSABLE, true);
                search.setArguments(b);
                search.show(getSupportFragmentManager(), POISearchDialogFragment.TAG);
            } else {
                res.setMessage("no actionCode found!");
                res.setStatus(0);
            }
            if (res == null) {
                res = new Res();
                res.setResult(new Object());
                delayCallback = function;
            } else if (res.getStatus() != -1) {
                function.onCallBack(FGson.gson().toJson(res));
                function = null;
            } else {
                delayCallback = function;
                function = null;
            }
        } catch (JSONException e) {
            res.setStatus(0);
            res.setMessage("json data format wrong!");
            function.onCallBack(FGson.gson().toJson(res));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (requestCode == FILECHOOSER_RESULTCODE && resultCode == RESULT_OK) {
            Uri result = intent == null ? null : intent.getData();
            if (result != null) {
                String path = MediaPathUtils.getImageAbsolutePath(result);
                DLog.e(TAG, path);
                try {
                    if(new File(path).exists() && FileSizeHelper.getFileOrFilesSize(path, FileSizeHelper.SIZETYPE_MB) > 5) {
                        res.setMessage("文件大小超过5M!");
                        res.setStatus(0);
                    }else {
                        res.setStatus(1);
                    }
                    JSONObject object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = object.getJSONObject("data");
                    if(res.getStatus() == 1)
                        data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + path);
                    if (delayCallback != null) {
                        delayCallback.onCallBack(object.toString());
                        delayCallback = null;
                    }
                } catch (JSONException e) {
                    DLog.p(e);
                }
            }
        } else if (requestCode == DecoderFragment.DECODER_REQUEST) {//二维码扫描
            String text = resultCode == RESULT_OK ? intent.getStringExtra(DecoderFragment.DECODER_RES) : null;
            try {
                if (text != null)
                    res.setStatus(1);
                else
                    res.setStatus(0);
                JSONObject object = new JSONObject(FGson.gson().toJson(res));
                JSONObject data = object.getJSONObject("data");
                data.put("code", text);
                if (delayCallback != null) {
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                }
            } catch (JSONException e) {
                res.setStatus(0);
                res.setMessage(e.getMessage());
            }
        } else if (requestCode == TAKEPICTURE_REQUESTCODE) {//照相
            try {
                if (resultCode == RESULT_OK)
                    res.setStatus(1);
                else
                    res.setStatus(0);
                final JSONObject object = new JSONObject(FGson.gson().toJson(res));
                final JSONObject data = new JSONObject();
                //data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + WebActivity.photoPath);
                object.put("data", data);

                if(res.getStatus() == 1){
                    final String path = "" + res.getResult();
                    data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + path);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            FileCacheUtil.convertThumbnail(path);
                            new Handler(Looper.getMainLooper()).post(new Runnable() {
                                @Override
                                public void run() {

                                    String da = data.toString();

                                    if (delayCallback != null) {
                                        delayCallback.onCallBack(object.toString());
                                        delayCallback = null;
                                    }
                                }
                            });

                        }
                    }).start();
                }
            } catch (JSONException e) {
                res.setStatus(0);
                res.setMessage(e.getMessage());
            }

        } else if (requestCode == GET_PICTURE_FROMTHUMB_REQUESTCODE && resultCode == RESULT_OK) {//图库获取图片
            Uri uri = intent.getData();
            if (uri != null) {
                try {
                    res.setStatus(1);
                    JSONObject object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = object.getJSONObject("data");
                    String path = MediaPathUtils.getImageAbsolutePath(uri);
                    FileCacheUtil.convertThumbnail(path);
                    data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + path);

                    if (delayCallback != null) {
                        delayCallback.onCallBack(object.toString());
                        delayCallback = null;
                    }
                } catch (JSONException e) {
                    res.setStatus(0);
                    res.setMessage(e.getMessage());
                }
            }
        } else if (requestCode == WebActivity.REQUEST_OPENFILE) {
            try {
                if (resultCode == Activity.RESULT_OK)
                    res.setStatus(1);
                else res.setStatus(0);
                JSONObject object = new JSONObject(FGson.gson().toJson(res));
                JSONObject data = object.getJSONObject("data");
                if (intent == null) {
                    data.put("deleted", false);
                } else {
                    data.put("deleted", intent.getBooleanExtra(ImageFragment.DELTED, false));
                }
                if (delayCallback != null) {
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                }
            } catch (JSONException e) {
                res.setStatus(0);
                res.setMessage(e.getMessage());
            }
        } else if (requestCode == REQUEST_STEP && resultCode == RESULT_OK) {
            res.setStatus(1);
            if (delayCallback != null) {
                delayCallback.onCallBack(FGson.gson().toJson(res));
                delayCallback = null;
            }
            setResult(RESULT_OK);
            if (webFragment != null)
                webFragment.clearCacheAndRefresh();
        } else if (requestCode == REQUEST_SUBPAGE_DATA) {
            String name = null;
            String data = null;
            try {
                name = intent.getStringExtra(WebActivity.PARENT_FUNCTION_NAME);
                data = intent.getStringExtra(WebActivity.PARENT_FUNCTION_DATA);
            } catch (Exception e) {
                DLog.p(e);
            }
            /*
            if(name != null && data != null && resultCode == RESULT_OK)
                res.setStatus(1);
            else
                res.setStatus(0);
            res.setMessage(name);
            //res.setData(FGson.gson().fromJson(data, LinkedHashMap.class));
            DLog.w("send", FGson.gson().toJson(res));
            //webFragment.send(FGson.gson().toJson(res));
            */
            webFragment.loadJS(name, data);
        } else if (requestCode == REQUEST_LOCATION) {
            ActionCallbacks.autoSign(object, this, delayCallback, true);
        }
        /*if (delayCallback != null) {
            res.setStatus(0);
            delayCallback.onCallBack(FGson.gson().toJson(res));
        }*/
        super.onActivityResult(requestCode, resultCode, intent);
    }

    /**
     * native调用弹窗操作
     *
     * @param b   dialogFragment回传数据
     * @param Tag fragment标志
     */
    @Override
    public void onRetrieveDialogFragmentData(Bundle b, int Tag) {
        if (b == null) {
            Toast.makeText(this, getResources().getString(R.string.error_field_required), Toast.LENGTH_SHORT).show();
            return;
        }
        switch (Tag) {
            case WritePadDialogFragment.WRITE_PAD:
                res.setStatus(1);
                JSONObject object = new JSONObject();
                try {
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = new JSONObject();
                    data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + b.getString("path"));
                    object.put("data", data);
                } catch (JSONException e) {
                    res.setStatus(0);
                    res.setMessage(e.getMessage());
                    DLog.p(e);
                }
                if (delayCallback != null) {
                    if (res.getStatus() == 1)
                        delayCallback.onCallBack(object.toString());
                    else
                        delayCallback.onCallBack(FGson.gson().toJson(res));
                    delayCallback = null;
                }
                break;
            case MSConstants.FragmentType.DIALOG_LOCATION_CHOICE_FRAGMENT:
                String addBack = b.getString("location");
                try {
                    if ("ADD_NEW_ADDRESS".equals(addBack)) {
                        res.setStatus(-1);
                    } else {
                        res.setStatus(1);
                    }
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = new JSONObject();
                    object.put("data", data);
                    if (!"ADD_NEW_ADDRESS".equals(addBack)) {
                        double latBack = b.getDouble("latitude");
                        double lngBack = b.getDouble("longtitude");
                        object.getJSONObject("data").put("location", addBack);
                        object.getJSONObject("data").put("latitude", latBack);
                        object.getJSONObject("data").put("longitude", lngBack);
                    }
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                } catch (JSONException e) {
                    DLog.p(e);
                }
                break;
            case MSConstants.FragmentType.DIALOG_CHOICE_FRAGMENT:
                int position = b.getInt(ChoiceConditionDialogFragment.POSITION, -1);
                try {
                    if(position != -1)
                        res.setStatus(1);
                    else
                        res.setStatus(1);
                    object = new JSONObject(FGson.gson().toJson(res));
                    if(res.getStatus() == 1) {
                        JSONObject data = object.getJSONObject("data");
                        data.put("index", position);
                        data.put("text", b.getString("text"));
                        try {
                            data.put("value", b.getString("value"));
                        }catch (Exception e){}
                    }
                    //data.put("value", b.getString("value"));
                    if (delayCallback != null) {
                        delayCallback.onCallBack(object.toString());
                        delayCallback = null;
                    }
                } catch (JSONException e) {
                    DLog.p(e);
                }
                break;
            case MSConstants.FragmentType.DIALOG_TIME_FRAGMENT:
                String time = b.getString(TimepickerDialogFragment.DATE);
                try {
                    res.setStatus(1);
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = object.getJSONObject("data");
                    data.put("time", time);
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                } catch (JSONException e) {
                    DLog.p(e);
                }
                break;
            case MSConstants.FragmentType.DIALOG_TALK_FRAGMENT:
                String path = b.getString("audio_path").isEmpty() ? "" : b.getString("audio_path");
                DLog.d("audio path:", path);
                try {
                    res.setStatus(1);
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = object.getJSONObject("data");
                    data.put("path", BridgeWebView.LOCAL_FILE_SCHEMA + path);
                    data.put("duration", FileHelper.getAmrDuration(new File(path)));
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                } catch (IOException | JSONException e) {
                    DLog.p(e);
                }

                break;
            case MSConstants.FragmentType.DIALOG_MORE_FRAGMENT:
                int actionId = b.getInt(OrderContentMoreDialogFragment.ACTION_ID);
                try {
                    if (actionId < 0)
                        res.setStatus(-1);
                    else
                        res.setStatus(1);
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = new JSONObject();
                    object.put("data", data);
                    object.getJSONObject("data").put("actionId", actionId);
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                } catch (JSONException e) {
                    DLog.p(e);
                }
                break;
            case MSConstants.FragmentType.DIALOG_SEARCH_FRAGMENT_MS:
                String address = b.getString("address");
                double latitude = b.getDouble("latitude");
                double longtitude = b.getDouble("longtitude");
                DLog.w("web:", address + "-" + latitude + "-" + longtitude);
                try {
                    res.setStatus(1);
                    object = new JSONObject(FGson.gson().toJson(res));
                    JSONObject data = new JSONObject();
                    object.put("data", data);
                    object.getJSONObject("data").put("location", address);
                    object.getJSONObject("data").put("latitude", latitude);
                    object.getJSONObject("data").put("longitude", longtitude);
                    delayCallback.onCallBack(object.toString());
                    delayCallback = null;
                    break;
                } catch (JSONException e) {
                    DLog.p(e);
                }
                break;
            case MSConstants.FragmentType.DIALOG_SEARCH_FRAGMENT:
                String selected = b.getString(POISearchDialogFragment.RESULT_KEY);
                SiteDao dao = MSApplication.getDaoSession().getSiteDao();
                List<Site> sites = dao.queryBuilder().where(SiteDao.Properties.Name.eq(selected)).list();
                if (sites != null && sites.size() > 0) {
                    Integer id = sites.get(0).getCustAddressId();
                    String name = sites.get(0).getName();
                    try {
                        res.setStatus(1);
                        object = new JSONObject(FGson.gson().toJson(res));
                        JSONObject data = new JSONObject();
                        object.put("data", data);
                        object.getJSONObject("data").put(POISearchDialogFragment.RESULT_KEY, name);
                        object.getJSONObject("data").put(POISearchDialogFragment.RESULT_VALUE, id);
                        delayCallback.onCallBack(object.toString());
                        delayCallback = null;
                        break;
                    } catch (JSONException e) {
                        DLog.p(e);
                    }
                }
                break;
        }
    }

    @Override
    public void finish() {
        //hold the webFragment after finish
        if (webFragment != null && webFragment.getView() != null) {
            webFragment.getView().startAnimation(AnimationUtils.loadAnimation(ContextManager.context(), R.anim.hold));
            /*
            String ticketid = ((Order) getIntent().getSerializableExtra(ORDER)).getTicketid();
            List<UrlSaver> savers = saverDao.queryBuilder().where(UrlSaverDao.Properties.Ticketid.eq(ticketid)).list();
            if (savers != null && savers.size() == 1) {
                DLog.i("url", "updating..." + "id:" + ticketid + "url:" + webFragment.getUrl());
                UrlSaver saver = savers.get(0);
                saver.setUrl(webFragment.getUrl());
                saverDao.update(saver);
            } else {
                DLog.i("url", "saving..." + "id:" + ticketid + "url:" + webFragment.getUrl());
                UrlSaver saver = new UrlSaver();
                saver.setUrl(webFragment.getUrl());
                saver.setTicketid(ticketid);
                saverDao.insert(saver);
            }
            */
        }
        //TODO result ok
        //setResult(Activity.RESULT_OK);
        super.finish();
    }

    @Override
    public void doPositiveClick(String tag) {
        res.setStatus(1);
        delayCallback.onCallBack(FGson.gson().toJson(res));
    }

    @Override
    public void doNegativeClick(String tag) {
        res.setStatus(0);
        delayCallback.onCallBack(FGson.gson().toJson(res));
    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        if (conn != null) {
            try {
                unbindService(conn);
            }catch (Exception e){}
        }
    }

    public RxFragment getWebFragment() {
        return webFragment;
    }
}


